package kef

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/kingeasts/keframe/request"
	"io/ioutil"
	"net/http"
)

type KeFrame struct {
	routes map[string]map[string]Route
	module string
}

func New() *KeFrame {
	data := make(map[string]map[string]Route)
	frame := &KeFrame{
		routes: data,
	}
	return frame
}

func (t *KeFrame) Module(m string) *KeFrame {
	t.module = m
	return t
}

func (t *KeFrame) AddRoute(method string, call Route) *KeFrame {
	if t.routes[t.module] == nil {
		t.routes[t.module] = make(map[string]Route)
	}
	t.routes[t.module][method] = call
	return t
}

func (t *KeFrame) Start(addr string) error {
	for k, _ := range t.routes {
		http.HandleFunc("/" + k, func(writer http.ResponseWriter, req *http.Request) {
			header := writer.Header()
			header.Add("Content-Type", "application/json")
			writer.WriteHeader(200)

			ctx := &Context{
				writer: writer,
				request: req,
			}
			body, err := ioutil.ReadAll(req.Body)
			if err != nil {
				ctx.Error(400, errors.New("请求结构错误"))
				return
			}
			var params request.Params
			if err = json.Unmarshal(body, &params); err != nil {
				ctx.Error(400, err)
				return
			}

			if t.routes[k] == nil || t.routes[k][params.Method] == nil {
				ctx.Error(404, errors.New("请求方法不存在"))
				return
			}
			ctx.Params = params.Args
			t.routes[k][params.Method](ctx)
		})
	}
	fmt.Printf("http start: %s\n", addr)
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		return err
	}
	return nil
}
